package com.example.chat.utils;


import com.example.chat.beans.Config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Data
@Component
public class Global {
    @Value("${global.config.website}")
    private String website;
    private String configJson;
    private Config config;

    public int packNum = 1;


    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat dateSdf = new SimpleDateFormat("yyyy-MM-dd");
    private SimpleDateFormat monthSdf = new SimpleDateFormat("yyyy-MM");
    private SimpleDateFormat yearSdf = new SimpleDateFormat("yyyy");

    private SimpleDateFormat numSdf = new SimpleDateFormat("yyyyMMddHH");
    private SimpleDateFormat dateNumSdf = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat monthNumSdf = new SimpleDateFormat("yyyyMM");
    private SimpleDateFormat yearNumSdf = new SimpleDateFormat("yyyy");

    private SimpleDateFormat hourSdf = new SimpleDateFormat("yyyy-MM-dd-HH");


    private SimpleDateFormat timeSdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    private List<String> suffix = Arrays.asList("jpeg", "jpg", "gif", "png");

    private List<String> suffixPhoto = Arrays.asList("jpeg", "jpg", "gif", "png");
    private List<String> suffixFile = Arrays.asList("html");
    private Map<String, Long> expireTime = new HashMap<>();

    /**
     * 中间4位使用*替换
     */
    public String mobileReplaceStar(String phone) {
        String result = null;
        if (!StringUtils.isEmpty(phone)) {
            if (phone.length() < 7) {
                result = phone;
            } else {
                String start = phone.substring(0, 3);
                String end = phone.substring(phone.length() - 4, phone.length());
                result = start + "****" + end;
            }
        }
        return result;
    }

    public static String getStringRandom() {
        Random random = new Random();
        //把随机生成的数字转成字符串
        StringBuilder str = new StringBuilder(String.valueOf(random.nextInt(9)));
        for (int i = 0; i < 5; i++) {
            str.append(random.nextInt(9));
        }
        return str.toString();
    }

    /**
     * long转string
     *
     * @param dateLong
     * @return
     */
    public static String longToString(long dateLong) {
        Date date = new Date(dateLong);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (dateLong != 0)
            return sdf.format(date);
        else return "";
    }

    public static Long StringToLong(String time) throws ParseException {
        if (time != null) {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).getTime();
        }
        return null;
    }

    public String plusZero(int num) {
        DecimalFormat decimalFormat = new DecimalFormat("00");
        return decimalFormat.format(num);
    }

    /**
     * 根据时间 和时间格式 校验是否正确
     *
     * @param length 校验的长度
     * @param sDate  校验的日期
     * @return
     */
    public static boolean isLegalDate(int length, String sDate, Integer type) {
        String format = "";
        if (type == 1) {
            format = "yyyy-MM-dd";
        }
        if (type == 2) {
            format = "yyyy-MM";
        }
        if (type == 3) {
            format = "yyyy";
        }
        if ((sDate == null) || (sDate.length() != length)) {
            return false;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }

    public static long getTodayStartEndTime(int type) {
        Date date = new Date(System.currentTimeMillis());
        Calendar today = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
        today.setTime(date);
        if (type == 1) {
            today.set(Calendar.HOUR_OF_DAY, 0);
            today.set(Calendar.MINUTE, 0);
            today.set(Calendar.SECOND, 0);
        }

        if (type == 2) {
            today.set(Calendar.HOUR_OF_DAY, 23);
            today.set(Calendar.MINUTE, 59);
            today.set(Calendar.SECOND, 59);
        }
        return today.getTime().getTime();
    }

    public static String plusUnit(int value) {
        DecimalFormat dF = new DecimalFormat("0.00");
        String str;
        if (value > 100000)
            str = dF.format((float) ((value) / 100000)) + "万";
        else
            str = String.valueOf(value);
        return str;
    }

    public static long datePlus(long start, int d) {
        Date date = new Date(start);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, d);
        return calendar.getTime().getTime();
    }

    public static String getRandom() {
        String num = "";
        for (int i = 0; i < 6; i++) {
            num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
        }
        return num;
    }

    public static String replaceFirstZero(String str) {
        return str.replaceFirst("^0*", "");
    }


    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位（B,K,M,G）
     * @return
     */
    public static boolean checkFileSize(Long len, double size, String unit) {
//        long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }

    public static String getBrowserType(HttpServletRequest request) {
        String type = "ie";
        String browserName = request.getHeader("USER-AGENT").toLowerCase();
        if (browserName.indexOf("msie") > 0) {
            type = "ie";
        }
        if (browserName.indexOf("firefox") > 0) {
            type = "firefox";
        }
        if (browserName.indexOf("chrome") > 0) {
            type = "chrome";
        }
        if (browserName.indexOf("opera") > 0) {
            type = "opera";
        }
        if (browserName.indexOf("gecko") > 0 && browserName.indexOf("rv:11") > 0) {
            type = "ie11";
        }
        return type;
    }

    public Integer strToIntTime(String time, int type) {
        if (time.equals(""))
            return 0;
        try {
            if (type == 1) {
                return Integer.parseInt(getNumSdf().format(getSdf().parse(time)));
            }
            if (type == 2) {
                return Integer.parseInt(getDateNumSdf().format(getDateSdf().parse(time)));
            }
            if (type == 3) {
                return Integer.parseInt(getMonthNumSdf().format(getMonthSdf().parse(time)));
            }
        } catch (ParseException parseException) {
            parseException.printStackTrace();
            return 0;
        }
        return 0;
    }


    public String intToStrTime(Integer time, int type) {
        try {
            if (type == 1) {
                return getSdf().format(getNumSdf().parse(String.valueOf(time)));
            }
            if (type == 2) {
                return getDateSdf().format(getDateNumSdf().parse(String.valueOf(time)));
            }
            if (type == 3) {
                return getMonthSdf().format(getMonthNumSdf().parse(String.valueOf(time)));
            }
        } catch (ParseException parseException) {
            parseException.printStackTrace();
            return "";
        }
        return "";
    }

    public void add(String uuid, Long time) {
        expireTime.put(uuid, time);
    }

}